package com.ocr.demo;

import javax.swing.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.List;

public class FileDropUploader extends JFrame {
    private JTextArea textArea;

    public FileDropUploader() {
        // 创建窗口和布局
        setTitle("File Drop Uploader");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);

        // 创建文本区域用于显示文件路径
        textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane);

        // 设置文本区域可接受拖拽操作
        textArea.setTransferHandler(new FileDropHandler());

        setVisible(true);
    }

    private class FileDropHandler extends TransferHandler {
        @Override
        public boolean canImport(TransferSupport support) {
            // 只允许拖拽操作导入文件
            return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
        }

        @Override
        public boolean importData(TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }

            // 获取拖拽操作中的文件列表
            Transferable transferable = support.getTransferable();
            try {
                List<File> fileList = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);

                // 处理每个文件
                for (File file : fileList) {
                    processFile(file);
                }

                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        private void processFile(File file) {
            // 处理文件的逻辑，这里只简单地将文件路径显示在文本区域中
            textArea.append(file.getAbsolutePath() + "\n");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(FileDropUploader::new);
    }
}
